﻿#if NETSTANDARD2_0_OR_GREATER || NET5_0_OR_GREATER
using System;
using System.Text.Json;
using System.Text.Json.Serialization;

using zijian666;
using zijian666.Core;
using zijian666.ConvertExtensions;

namespace zijian666.Json;

/// <summary>
/// 替换默认json转换器
/// </summary>
/// <typeparam name="T"></typeparam>
internal class JsonValueConverter<T> : JsonConverter<T>
{
    public override bool CanConvert(Type type)
        => type == typeof(T);

    public override T? Read(ref Utf8JsonReader reader, Type type, JsonSerializerOptions options)
    {
        var value = JsonSerializer.Deserialize<string>(ref reader, options);

        var result = (ConvertContext.Current?.Convert(type, value)) ?? value.Convert(type);
        return (T?)result.Value;
    }

    public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
    {
        var result = (ConvertContext.Current?.Convert<string>(value)) ?? value.Convert<string>();
        if (result.Success == true)
        {
            JsonSerializer.Serialize(writer, result.Value, options);
        }
        else
        {
            JsonSerializer.Serialize(writer, value, options);
        }
    }
}

#endif